package com.woniuxy.project115.kaer.mall.service.impl;

import cn.hutool.json.JSONUtil;
//import com.alipay.api.AlipayApiException;
//import com.alipay.api.AlipayClient;
//import com.alipay.api.request.AlipayTradeQueryRequest;
//import com.alipay.api.request.AlipayTradeRefundRequest;
//import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project115.kaer.mall.entity.OrderLog;
import com.woniuxy.project115.kaer.mall.entity.ProductOrderInfo;
import com.woniuxy.project115.kaer.mall.entity.Refund;
import com.woniuxy.project115.kaer.mall.mapper.OrderLogMapper;
import com.woniuxy.project115.kaer.mall.mapper.ProductOrderInfoMapper;
import com.woniuxy.project115.kaer.mall.mapper.RefundMapper;
import com.woniuxy.project115.kaer.mall.service.ProductOrderInfoService;
import com.woniuxy.project115.kaer.mall.service.RefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project115.kaer.user.feign.UserFeignClient;
import com.woniuxy.project115.kaer.user.form.ScoreChangeForm;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyc
 * @since 2025年02月26日
 */
@Service
public class RefundServiceImpl extends ServiceImpl<RefundMapper, Refund> implements RefundService {
    @Resource
    private RefundMapper refundMapper;
    @Resource
    private ProductOrderInfoMapper productOrderInfoMapper;
//    @Resource
//    private AlipayClient alipayClient;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private OrderLogMapper orderLogMapper;

    @Override
    public void refundApply(String orderNum, String reason, Integer userId) throws Exception {
        ProductOrderInfo productOrderInfo = productOrderInfoMapper.selectOne(new QueryWrapper<ProductOrderInfo>().eq("user_id",userId).eq("order_num", orderNum).eq("pay_state", "已支付"));
        if (productOrderInfo == null) {
            throw new Exception("订单不存在或未支付");
        }
        //查询实际付款金额
//        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNum+"\"}");
//        String result = alipayClient.execute(alipayRequest).getBody();
//        System.out.println(result);

//        String payMoney= JSONUtil.parseObj(result).getJSONObject("alipay_trade_query_response").get("total_amount").toString();
        String payMoney=productOrderInfo.getRealPay().toString();
        BigDecimal amount = new BigDecimal(payMoney);
        int score =  productOrderInfo.getTotalPrice().intValue()-((int) Double.parseDouble(payMoney));
        Refund refund = new Refund();
        refund.setRefundReason(reason);
        refund.setOrderNum(orderNum);
        refund.setRefundState(1);//待审核
        refund.setAmount(amount);
        refund.setScore(score);
        refund.setCreateTime(LocalDateTime.now());
        refund.setOrderPrice(productOrderInfo.getTotalPrice());
        refundMapper.insert(refund);
        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNum(orderNum);
        orderLog.setOperateType("用户申请退款");
        orderLog.setOperateTime(LocalDateTime.now());
        orderLog.setUserId(userId);
        orderLogMapper.insert(orderLog);
    }

    @Override
    public List<Refund> refundList() {
        return refundMapper.selectList(new QueryWrapper<Refund>().orderByDesc("create_time"));
    }

    @Override
    public void refundAudit(Integer refundId,String reason, String operate) throws Exception {
        Refund refund = refundMapper.selectOne(new QueryWrapper<Refund>().eq("refund_id", refundId).eq("refund_state", "1"));
        if (refund == null) {
            throw new Exception("退款申请不存在");
        }
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNum(refund.getOrderNum());
        orderLog.setOperateTime(LocalDateTime.now());
        orderLog.setUserId(1);
        if (refund.getRefundState() == 1) {
            if(operate.equals("同意")){
                refund.setRefundState(2);
                refund.setRemarks("同意退款");
                refundMapper.updateById(refund);
                //更改订单状态
                ProductOrderInfo productOrderInfo = productOrderInfoMapper.selectById(refund.getOrderNum());
                productOrderInfo.setPayState("退款中");
                productOrderInfoMapper.updateById(productOrderInfo);
                orderLog.setOperateType("管理员同意退款");
                //异步发送给消息队列完成退款
                rabbitTemplate.convertAndSend("refund","refund_key",refundId);
            } else if (operate.equals("拒绝")) {
                refund.setRefundState(3);
                refund.setRemarks(reason);
                refundMapper.updateById(refund);
                orderLog.setOperateType("管理员拒绝退款");
            }
            orderLogMapper.insert(orderLog);
        }
    }

    @Override
    public void handleRefund(Integer applyId) {
        Refund refund = refundMapper.selectById(applyId);
        if (refund == null) {
            System.err.println("退款申请不存在，申请 ID: " + applyId);
            return;
        }

//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//        request.setBizContent("{\"out_trade_no\":\"" + refund.getOrderNum() + "\","
//                + "\"refund_amount\":\"" + refund.getAmount().toString() + "\","
//                + "\"refund_reason\":\"" + refund.getRefundReason() + "\"}");

        try {
//            AlipayTradeRefundResponse response = alipayClient.execute(request);

//            if (response.isSuccess()) {
            if (true){
                // 退款成功，更新退款状态
                refund.setRefundState(4);
                refundMapper.updateById(refund);
                //返还用户积分
                ScoreChangeForm scoreChangeForm = new ScoreChangeForm();
                scoreChangeForm.setUserId(productOrderInfoMapper.selectById(refund.getOrderNum()).getUserId());
                scoreChangeForm.setScore(refund.getScore());
                scoreChangeForm.setType("加");
                userFeignClient.scoreChange(scoreChangeForm);
                System.out.println("退款成功，申请 ID: " + applyId);
            } else {
                // 退款失败，更新退款状态
                refund.setRefundState(2);
                refundMapper.updateById(refund);
//                System.err.println("退款失败，申请 ID: " + applyId + ", 错误码: " + response.getCode() + ", 错误信息: " + response.getMsg());
                System.err.println("退款失败，申请 ID: " + applyId );

            }
        } catch (Exception e) {
            e.printStackTrace();
            // 退款异常，更新退款状态
            refund.setRefundState(2);
            refundMapper.updateById(refund);
            System.err.println("退款异常，申请 ID: " + applyId + ", 异常信息: " + e.getMessage());
        }
    }
}
